'use client'

import React, { useState, useEffect } from 'react'
import {
    Drawer,
    Tabs,
    Switch,
    Button,
    Card,
    Space,
    Typography,
    Badge,
    List,
    Tag,
    Collapse,
    Input,
    Select,
    Divider,
    Alert
} from 'antd'
import {
    BugOutlined,
    ApiOutlined,
    DatabaseOutlined,
    SettingOutlined,
    ClearOutlined,
    DownloadOutlined,
    ReloadOutlined
} from '@ant-design/icons'
import { useDevToolsStore } from '@/stores/devToolsStore'
import MockDataTester from './MockDataTester'

const { Title, Text, Paragraph } = Typography
const { TabPane } = Tabs
const { Panel } = Collapse
const { TextArea } = Input
const { Option } = Select

interface DevToolsPanelProps {
    visible: boolean
    onClose: () => void
}

export function DevToolsPanel({ visible, onClose }: DevToolsPanelProps) {
    const {
        isEnabled,
        useMockApi,
        apiLogs,
        debugInfo,
        mockDataMode,
        toggleDevTools,
        toggleMockApi,
        clearApiLogs,
        addApiLog,
        setMockDataMode,
        exportLogs
    } = useDevToolsStore()

    const [selectedLogLevel, setSelectedLogLevel] = useState<string>('all')

    // 过滤API日志
    const filteredLogs = apiLogs.filter(log => {
        if (selectedLogLevel === 'all') return true
        return log.level === selectedLogLevel
    })

    // 模拟数据模式选项
    const mockDataModes = [
        { value: 'default', label: '默认数据' },
        { value: 'large', label: '大数据集' },
        { value: 'error', label: '错误场景' },
        { value: 'empty', label: '空数据' },
        { value: 'slow', label: '慢响应' }
    ]

    // 手动添加测试日志
    const addTestLog = () => {
        addApiLog({
            id: `test_${Date.now()}`,
            timestamp: new Date(),
            method: 'GET',
            url: '/api/test',
            status: 200,
            duration: 150,
            level: 'info',
            request: { headers: { 'Content-Type': 'application/json' } },
            response: { data: { message: 'Test log entry' } }
        })
    }

    return (
        <Drawer
            title={
                <Space>
                    <BugOutlined />
                    <span>开发者工具</span>
                    <Badge
                        count={apiLogs.length}
                        size="small"
                        style={{ backgroundColor: '#52c41a' }}
                    />
                </Space>
            }
            placement="right"
            width={600}
            open={visible}
            onClose={onClose}
            bodyStyle={{ padding: 0 }}
        >
            <Tabs defaultActiveKey="api" style={{ height: '100%' }}>
                <TabPane
                    tab={
                        <Space>
                            <ApiOutlined />
                            API 日志
                            <Badge count={apiLogs.length} size="small" />
                        </Space>
                    }
                    key="api"
                >
                    <div style={{ padding: 16 }}>
                        <Space direction="vertical" style={{ width: '100%' }}>
                            {/* API日志控制 */}
                            <Card size="small" title="日志控制">
                                <Space wrap>
                                    <Select
                                        value={selectedLogLevel}
                                        onChange={setSelectedLogLevel}
                                        style={{ width: 120 }}
                                    >
                                        <Option value="all">全部</Option>
                                        <Option value="info">信息</Option>
                                        <Option value="warn">警告</Option>
                                        <Option value="error">错误</Option>
                                    </Select>
                                    <Button
                                        icon={<ClearOutlined />}
                                        onClick={clearApiLogs}
                                        size="small"
                                    >
                                        清空日志
                                    </Button>
                                    <Button
                                        icon={<DownloadOutlined />}
                                        onClick={exportLogs}
                                        size="small"
                                    >
                                        导出日志
                                    </Button>
                                    <Button
                                        icon={<ApiOutlined />}
                                        onClick={addTestLog}
                                        size="small"
                                        type="dashed"
                                    >
                                        添加测试日志
                                    </Button>
                                </Space>
                            </Card>

                            {/* API日志列表 */}
                            <Card
                                size="small"
                                title={`API 调用日志 (${filteredLogs.length})`}
                                style={{ maxHeight: 400, overflow: 'auto' }}
                            >
                                <List
                                    size="small"
                                    dataSource={filteredLogs.slice(-20)} // 只显示最近20条
                                    renderItem={(log) => (
                                        <List.Item>
                                            <Collapse size="small" style={{ width: '100%' }}>
                                                <Panel
                                                    header={
                                                        <Space>
                                                            <Tag color={log.status >= 400 ? 'red' : 'green'}>
                                                                {log.method}
                                                            </Tag>
                                                            <Text code>{log.url}</Text>
                                                            <Tag>{log.status}</Tag>
                                                            <Text type="secondary">{log.duration}ms</Text>
                                                            <Text type="secondary">
                                                                {log.timestamp.toLocaleTimeString()}
                                                            </Text>
                                                        </Space>
                                                    }
                                                    key={log.id}
                                                >
                                                    <Space direction="vertical" style={{ width: '100%' }}>
                                                        <div>
                                                            <Text strong>请求:</Text>
                                                            <TextArea
                                                                value={JSON.stringify(log.request, null, 2)}
                                                                rows={3}
                                                                readOnly
                                                            />
                                                        </div>
                                                        <div>
                                                            <Text strong>响应:</Text>
                                                            <TextArea
                                                                value={JSON.stringify(log.response, null, 2)}
                                                                rows={3}
                                                                readOnly
                                                            />
                                                        </div>
                                                    </Space>
                                                </Panel>
                                            </Collapse>
                                        </List.Item>
                                    )}
                                />
                            </Card>
                        </Space>
                    </div>
                </TabPane>

                <TabPane
                    tab={
                        <Space>
                            <DatabaseOutlined />
                            模拟数据
                        </Space>
                    }
                    key="mock"
                >
                    <MockDataTester />
                </TabPane>

                <TabPane
                    tab={
                        <Space>
                            <DatabaseOutlined />
                            数据配置
                        </Space>
                    }
                    key="config"
                >
                    <div style={{ padding: 16 }}>
                        <Space direction="vertical" style={{ width: '100%' }}>
                            {/* 模拟API开关 */}
                            <Card size="small" title="模拟API设置">
                                <Space direction="vertical" style={{ width: '100%' }}>
                                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                        <Text>启用模拟API</Text>
                                        <Switch
                                            checked={useMockApi}
                                            onChange={toggleMockApi}
                                            checkedChildren="开启"
                                            unCheckedChildren="关闭"
                                        />
                                    </div>

                                    {useMockApi && (
                                        <>
                                            <Divider />
                                            <div>
                                                <Text strong>模拟数据模式:</Text>
                                                <Select
                                                    value={mockDataMode}
                                                    onChange={setMockDataMode}
                                                    style={{ width: '100%', marginTop: 8 }}
                                                >
                                                    {mockDataModes.map(mode => (
                                                        <Option key={mode.value} value={mode.value}>
                                                            {mode.label}
                                                        </Option>
                                                    ))}
                                                </Select>
                                            </div>

                                            <Alert
                                                message="模拟API已启用"
                                                description="当前使用模拟数据进行开发和测试。切换到生产模式时请关闭此选项。"
                                                type="info"
                                                showIcon
                                            />
                                        </>
                                    )}
                                </Space>
                            </Card>
                        </Space>
                    </div>
                </TabPane>

                <TabPane
                    tab={
                        <Space>
                            <SettingOutlined />
                            调试信息
                        </Space>
                    }
                    key="debug"
                >
                    <div style={{ padding: 16 }}>
                        <Space direction="vertical" style={{ width: '100%' }}>
                            {/* 系统信息 */}
                            <Card size="small" title="系统信息">
                                <Space direction="vertical" style={{ width: '100%' }}>
                                    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                        <Text>环境:</Text>
                                        <Tag color="blue">{process.env.NODE_ENV}</Tag>
                                    </div>
                                    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                        <Text>API地址:</Text>
                                        <Text code>{process.env.NEXT_PUBLIC_API_BASE_URL}</Text>
                                    </div>
                                    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                        <Text>模拟API:</Text>
                                        <Tag color={useMockApi ? 'green' : 'red'}>
                                            {useMockApi ? '启用' : '禁用'}
                                        </Tag>
                                    </div>
                                    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                        <Text>时间戳:</Text>
                                        <Text type="secondary">{new Date().toLocaleString()}</Text>
                                    </div>
                                </Space>
                            </Card>

                            {/* 调试信息 */}
                            <Card size="small" title="调试信息">
                                <TextArea
                                    value={JSON.stringify(debugInfo, null, 2)}
                                    rows={10}
                                    readOnly
                                    placeholder="调试信息将显示在这里..."
                                />
                            </Card>

                            {/* 快速操作 */}
                            <Card size="small" title="快速操作">
                                <Space wrap>
                                    <Button
                                        icon={<ReloadOutlined />}
                                        onClick={() => window.location.reload()}
                                    >
                                        刷新页面
                                    </Button>
                                    <Button
                                        onClick={() => localStorage.clear()}
                                    >
                                        清空本地存储
                                    </Button>
                                    <Button
                                        onClick={() => sessionStorage.clear()}
                                    >
                                        清空会话存储
                                    </Button>
                                    <Button
                                        onClick={() => console.clear()}
                                    >
                                        清空控制台
                                    </Button>
                                </Space>
                            </Card>
                        </Space>
                    </div>
                </TabPane>
            </Tabs>
        </Drawer>
    )
}

export default DevToolsPanel